在 C++11 之前,C++ 标准是 “与线程无关”, 依赖于平台特定的 API,如 POSIX 线程(Pthreads)或 Win32。现代 C++ 通过引入一个正式的 内存模型 和一个标准化的并发 API,彻底革新了这门语言。
1. C++11 的“根本性变革”
C++11 将语言从单线程抽象机转变为一种原生支持并发执行的语言,通过 <thread> 头文件和 std::thread实现了并发。这使多线程不再只是外部库的问题,而是成为核心类型系统的一部分。
2. 异常保证
在并发环境中, noexcept 说明符至关重要。它提供了一个契约,即函数(如线程入口点)不会传播异常。如果异常突破了 noexcept 边界, std::terminate() 将立即被调用,防止未定义状态的破坏。
3. 一致的数据类型
标准化包含了像 long long int (源自 C99)以及 std::filesystem这样的类型,确保在不同硬件间共享数据时,数据宽度和系统交互保持一致。
noexcept specifier in a multi-threaded application?It makes the code execute faster by disabling all memory barriers.
It prevents data races automatically.
It guarantees a function won't throw, allowing optimizations and preventing std::terminate on escape.
It forces the thread to run on a single core.
int64_t
long long int
std::atomic_int
size_t
True
False
noexcept calls a function that throws an exception?The exception is caught and ignored.
The compiler replaces it with a return 0.
The program immediately calls std::terminate().
The program pauses the thread until a debugger is attached.
Use
std::thread from the <thread> header. This abstracts the OS-level thread creation and works identically across Windows, Linux, and macOS.Use
long long int, which guarantees at least 64 bits of precision and was formally adopted into C++11 for cross-platform data width consistency.Mark the thread's entry-point lambda or function as
noexcept. This documents that the logger shouldn't throw and allows the compiler to optimize, while explicitly handling internal errors within the scope.